package com.example.spring_gobang.controller;

import com.example.spring_gobang.common.AjaxResult;
import com.example.spring_gobang.common.AppVariable;
import com.example.spring_gobang.model.UserInfo;
import com.example.spring_gobang.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    /**
     * 登录功能
     */
    @RequestMapping("/login")
    public AjaxResult login(String username,String password,HttpServletRequest request){
        if (!StringUtils.hasLength(username) ||
        !StringUtils.hasLength(password)){
            return AjaxResult.fail(-1,"非法参数！");
        }
        UserInfo userInfo = userService.selectByNamePassword(username,password);
        userInfo.setPassword("");
        HttpSession session = request.getSession(true);
        session.setAttribute(AppVariable.USER_SESSION_KEY,userInfo);
        return AjaxResult.success(200,userInfo);
    }

    /**
     *注册账号
     */
    @RequestMapping("/reg")
    public AjaxResult reg(String username,String password){
        if (!StringUtils.hasLength(username) ||
        !StringUtils.hasLength(password)){
            return AjaxResult.fail(-1,"非法参数");
        }
        Integer n = userService.insertAndReg(username,password);
        if (n == 1){
            return AjaxResult.success(200,n);
        }else {
            return AjaxResult.fail(-1,"用户名已存在 请重新注册！");
        }
    }
    /**
     * 进入游戏大厅页面 根据用户名查找用户身份信息
     */
    @RequestMapping("/getUserinfo")
    public AjaxResult getUserByName(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        UserInfo userInfo = (UserInfo) session.getAttribute(AppVariable.USER_SESSION_KEY);
        //这里返回大厅的时候保存的用的还是session中存的旧的信息 要重新从数据库中读一次返回
        UserInfo newUser = userService.selectByName(userInfo.getUsername());
        return AjaxResult.success(200,newUser);
    }
}
